package com.itheima.health.h5.controller;

import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisMessageConstant;
import com.itheima.health.utils.sms.ValidateCodeUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class OrderController {

    @Reference
    private OrderService orderService;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("order/sendMessage/{telephone}")
    public Result sendMessage(@PathVariable("telephone")String  telephone){
        //  存放 redis    阿里云发送短信
        String code = ValidateCodeUtils.generateValidateCode(4);
        RedisUtil.set(RedisMessageConstant.SENDTYPE_ORDER+telephone,code,90, TimeUnit.SECONDS);
       // mq  发送发短信内容 消息形式 投递 mq  队列上
        Map map = new HashMap();
        map.put("telephone",telephone);
        map.put("code",code);
//        rabbitTemplate.convertAndSend("sms-exchange","",map);
        return  new Result(code);
    }

    @GetMapping("order/findOrderInfoById/{id}")
    public Result findOrderInfoById(@PathVariable("id")int  id){
        return  new Result(orderService.findOrderInfoById(id));
    }

    @PostMapping("order/add")
    public Result add(@RequestBody Map map){
        Order order = orderService.add(map);
        String uuid = UUID.randomUUID().toString();
        MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //消息持久化
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                // 模拟，设置10S后消息过期
                message.getMessageProperties().setExpiration("180000");
                return message;
            }
        };
        rabbitTemplate.convertAndSend("order-exchange","",String.valueOf(order.getId()),messagePostProcessor,new CorrelationData(uuid));
        return  new Result(order);
    }

}
